package com.hunnyhu.tools;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SignDao {
	
	//获得 helper对象用来操纵数据库  
    private DBHelper mHelper = null; 
    private SQLiteDatabase db = null;
    
    public SignDao(Context context) {  
        mHelper = new DBHelper(context);  
		db = mHelper.getWritableDatabase();
    }
    
	public Long checkIn(Date checkInDate) {
		return saveCheckDate(checkInDate, DBHelper.C_DATE_BEGIN);
	}
	
	public Long checkOut(Date checkOutDate) {
		return saveCheckDate(checkOutDate, DBHelper.C_DATE_END);
	}
	
	public int deleteByPrimaryKey(String id) {
		return db.delete(DBHelper.T_SIGN, DBHelper.C_ID + " = ?", new String[] {id});
	}
	
	public int updateCheckDate(Date signInDate, Date signOutDate, String id) {
		ContentValues values = new ContentValues();
		if (null != signInDate) {
	        values.put(DBHelper.C_DATE_BEGIN, Utils.dateToString(signInDate));
		}
		if (null != signOutDate) {
	        values.put(DBHelper.C_DATE_END, Utils.dateToString(signOutDate));
		}
		values.put(DBHelper.C_LAST_UPDATED, Utils.dateToString(new Date()));
		return db.update(DBHelper.T_SIGN, values, DBHelper.C_ID + " = ?", new String[] {id});
	}
	
	protected Long saveCheckDate(Date check, String column) {
		try {
			Date cDate = new Date();
			ContentValues values = new ContentValues();  
            values.put(column, Utils.dateToString(check));
            Map<String, Object> map = findByDate(check);
            values.put(DBHelper.C_LAST_UPDATED, Utils.dateToString(cDate));
            if (null != map && !map.isEmpty()) {
            	Integer i = db.update(DBHelper.T_SIGN, values, DBHelper.C_ID + " = ?", new String[] {(String)map.get(DBHelper.C_ID)});
            	return i.longValue();
            } else {
                values.put(DBHelper.C_DATE_CREATED, Utils.dateToString(cDate));
                return db.insert(DBHelper.T_SIGN, null, values);
            }
		} finally {
		     db.close();
		}
	}
	
	public List<Map<String, Object>> findByCheckInDate(Date checkInDate) {
		return findByCheckDate(checkInDate, DBHelper.C_DATE_BEGIN);
	}
	
	public List<Map<String, Object>> findByCheckOutDate(Date checkOutDate) {
		return findByCheckDate(checkOutDate, DBHelper.C_DATE_END);
	}
	
	protected List<Map<String, Object>> findByCheckDate(Date checkDate, String column) {
		if (null == checkDate) {
			return Collections.emptyList();
		}
		String bDate = Utils.dateToString(checkDate, Utils.YYYY_MM_DD);
		String sDate = bDate + " 00:00:00";
		String eDate = bDate + " 23:59:59";
		return findByTable(DBHelper.T_SIGN, columns(), 
				column + " >= ?" + " and " + column + " <= ?",
				new String[] {sDate, eDate}, null, null, null);
	}
	
	protected Map<String, Object> findById(String id) {
		String where = null;
		String [] whereArgs = null;
		if (null != id) {
			where = DBHelper.C_ID + " = ?";
			whereArgs = new String[] {
				id
			};
		}
		List<Map<String, Object>> list = findByTable(DBHelper.T_SIGN, columns(), where,
				whereArgs, null, null, "id desc limit 1");
		if (null == list || list.isEmpty()) {
			return Collections.emptyMap();
		}
		return list.get(0);
	}
	
	protected List<Map<String, Object>> findListByDate(String id) {
		String where = null;
		String [] whereArgs = null;
		if (null != id) {
			where = DBHelper.C_ID + " < ?";
			whereArgs = new String[] {
				id
			};
		}
		return findByTable(DBHelper.T_SIGN, columns(), where,
				whereArgs, null, null, "id desc limit 10");
	}
	
	public Map<String, Object> findByDate(Date date) {
		String bDate = Utils.dateToString(date, Utils.YYYY_MM_DD);
		String sDate = bDate + " 00:00:00";
		String eDate = bDate + " 23:59:59";
		List<Map<String, Object>> list = findByTable(DBHelper.T_SIGN, columns(), 
				"(" + DBHelper.C_DATE_BEGIN + " >= ?" + " and " + DBHelper.C_DATE_BEGIN + " <= ? ) "
				+ " or " + 
				"(" + DBHelper.C_DATE_END + " >= ?" + " and " + DBHelper.C_DATE_END + " <= ? ) ",
				new String[] {sDate, eDate, sDate, eDate}, null, null, "id desc limit 1");
		if (null == list || list.isEmpty()) {
			return Collections.emptyMap();
		}
		return list.get(0);
	}
	
	protected List<Map<String, Object>> findByTable(String table, String [] columns, String where, String [] whereArgs, String groupBy, String having, String orderBy) {
		SQLiteDatabase db = mHelper.getReadableDatabase();
		Cursor cursor = db.query(table, columns, where, whereArgs, groupBy, having, orderBy);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		while (cursor.moveToNext()) {
			Map<String, Object> result = formatCursor(cursor);
			list.add(result);
		}
		return list;
	}
	
	protected String [] columns() {
		return new String[] {DBHelper.C_ID, DBHelper.C_DATE_BEGIN, DBHelper.C_DATE_END, DBHelper.C_DATE_CREATED, DBHelper.C_LAST_UPDATED};
	}
	
	private Map<String, Object> formatCursor(Cursor cursor) {
		Map<String, Object> map = new HashMap<String, Object>();
		String [] columns = columns();
		for (String col : columns) {
			map.put(col, cursor.getString(cursor.getColumnIndex(col)));
		}
		return map;
	}
	
}
